from django import forms
from django.core import validators
from .models import User


class BaseForm(forms.Form):
    # {'telphone': [{'message': '18688888888手机号已存在', 'code': ''}]}
    def get_errors(self):
        errors = self.errors.get_json_data()
        new_error = {}
        for key, errmsgs in errors.items():
            messages = []
            for errmsg in errmsgs:
                messages.append(errmsg.get('message'))
            new_error[key] = messages
        return new_error


class MyForm(BaseForm):
    # email = forms.EmailField(error_messages={'required': '邮箱输入不能为空', 'invalid': '邮箱格式输入不正确'})
    # price = forms.FloatField(min_value=0, max_value=10000,
    #                          error_messages={'min_value': '最小输入0', 'max_value': '最大输入10000', 'required': 'price 输入不能为空',
    #                                          'invalid': 'price 输入非法'})
    # website = forms.URLField(error_messages={'required': 'website 不能为空', 'invalid': 'website 输入非法'})

    # TODO: 常用验证器
    email = forms.CharField(validators=[validators.EmailValidator(message='输入邮箱格式不正确')])
    telphone = forms.CharField(validators=[validators.RegexValidator(regex=r'^1[356789]\d{9}$', message='输入手机号码格式不正确')])


class SignUpForm(BaseForm):
    username = forms.CharField(min_length=6, max_length=12,
                               error_messages={'min_length': '用户昵称最少6个字符', 'max_length': '用户昵称不超过12个字符'})
    telphone = forms.CharField(min_length=11, max_length=11,
                               error_messages={'min_length': '手机号为11位数字', 'max_length': '手机号为11位数字'})
    psd1 = forms.CharField(min_length=6, max_length=12,
                           error_messages={'min_length': '密码为6-12位字符', 'max_length': '密码为6-12位字符'})
    psd2 = forms.CharField(min_length=6, max_length=12,
                           error_messages={'min_length': '密码为6-12位字符', 'max_length': '密码为6-12位字符'})

    # TODO: 对某个字段进行自定义的验证方式是，定义一个方法，这个方法的名字定义规则是：clean_fieldname。
    #  如果验证失败，那么就抛出一个验证错误
    def clean_telphone(self):
        telphone = self.cleaned_data.get('telphone')
        exists = User.objects.filter(telphone=telphone).exists()
        if exists:
            raise forms.ValidationError(message='%s手机号已存在' % telphone)
        return telphone

    # TODO: 如果验证数据的时候，需要针对多个字段进行验证，那么可以重写clean方法
    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()
        psd1 = cleaned_data.get('psd1')
        psd2 = cleaned_data.get('psd2')
        if psd1 != psd2:
            raise forms.ValidationError(message='两次密码输入不一致')
        return cleaned_data
